/*
* This software is licensed under the GNU General Public License, version 2
* You may copy, distribute and modify the software as long as you track changes/dates of in source files and keep all modifications under GPL. You can distribute your application using a GPL library commercially, but you must also provide the source code.

* DNNspot Software (http://www.dnnspot.com)
* Copyright (C) 2013 Atriage Software LLC
* Authors: Kevin Southworth, Matthew Hall, Ryan Doom

* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.

* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.

* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

* Full license viewable here: http://www.gnu.org/licenses/gpl-2.0.txt
*/

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Services;
using DNNspot.LiveChat.DataModel;
using DotNetNuke.Entities.Users;
using EntitySpaces.DynamicQuery;
using EntitySpaces.Interfaces;


namespace DNNspot.LiveChat
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class QueueHandler : IHttpHandler
    {
        // PRIVATE MEMBERS #######################################################

        // PUBLIC METHODS ########################################################

        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;

            var portalId = Convert.ToInt32(request.QueryString["portalId"] ?? "0");

            context.Response.Expires = -1;
            context.Response.ContentType = "application/json";

            InitializeProvider();

            response.Write(BuildOutputString(portalId));
            response.Flush();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        // PRIVATE METHODS #######################################################

        private static string BuildOutputString(int portalId)
        {
            var output = string.Empty;
            var rowOutput = string.Empty;

            var q = new SessionQuery();
            q.Where(q.PortalId == portalId);
            q.Where(q.AgentId.IsNull() && q.IsActive == true);
            q.OrderBy(q.CreatedDate.Ascending);

            var sessions = new SessionCollection();
            sessions.Load(q);

            foreach (Session session in sessions)
            {
                if (rowOutput.Length > 0)
                    rowOutput += ",";


                rowOutput += string.Format("{{id:{0},cell:['{1}','{2}','{3}', '{4}']}}",
                        session.SessionId,
                        Convert.ToDateTime(session.CreatedDate),
                        string.Format("{0} {1}", session.UpToClientByClientId.FirstName, session.UpToClientByClientId.LastName).Replace("'", "\\'"),
                        session.UpToCategoryByCategoryId.Name,
                        Elipsis(session.Notes, 40).Replace("\n", " ").Replace("\r", " ").Replace("'", "\\\'")
                        );
            }

            output += string.Format("{{rows: [{0}]}}", rowOutput);

            return output;
        }

        private static string Elipsis(string text, int length)
        {
            if (string.IsNullOrEmpty(text))
                return string.Empty;

            if(text.Length > length)
            {
                text = text.Substring(0, length).TrimEnd() + "...";
            }

            return text;
        }

        private static void InitializeProvider()
        {
            if (esConfigSettings.ConnectionInfo.Default != "SiteSqlServer")
            {
                esConfigSettings connectionInfoSettings = esConfigSettings.ConnectionInfo;
                foreach (esConnectionElement connection in connectionInfoSettings.Connections)
                {
                    //if there is a SiteSqlServer in es connections set it default
                    if (connection.Name == "SiteSqlServer")
                    {
                        esConfigSettings.ConnectionInfo.Default = connection.Name;
                        return;
                    }
                }

                //no SiteSqlServer found grab dnn cnn string and create
                string dnnConnection = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

                // Manually register a connection
                esConnectionElement conn = new esConnectionElement();
                conn.ConnectionString = dnnConnection;
                conn.Name = "SiteSqlServer";
                conn.Provider = "EntitySpaces.SqlClientProvider";
                conn.ProviderClass = "DataProvider";
                conn.SqlAccessType = esSqlAccessType.DynamicSQL;
                conn.ProviderMetadataKey = "esDefault";
                conn.DatabaseVersion = "2005";

                // Assign the Default Connection
                esConfigSettings.ConnectionInfo.Connections.Add(conn);
                esConfigSettings.ConnectionInfo.Default = "SiteSqlServer";

                // Register the Loader
                esProviderFactory.Factory = new EntitySpaces.LoaderMT.esDataProviderFactory();
            }
        }
    }
}
